package panda.query.tree;

import java.util.List;

import panda.file.Page;
import panda.query.scan.Scanner;
import panda.query.struct.Attribute;
import panda.query.util.MergeSorter;
import panda.query.util.OrderByComparator;
import panda.record.Schema;
import panda.record.TableToken;
import panda.transaction.Transaction;

public class OrderByNode implements QueryTreeNode {
	
	QueryTreeNode q;
	List<Attribute> attrs;
	List<Boolean> order;
	Transaction tx;
	
	public OrderByNode(QueryTreeNode q, List<Attribute> attrs, List<Boolean> order, Transaction tx) {
		this.q = q;
		this.attrs = attrs;
		this.order = order;
		this.tx = tx;
	}
	
	@Override
	public Scanner open() {
//		TempTable t = new TempTable(q.getSchema(), tx);
//		t.copyFrom(q.open());
//		t.sort(attrs, order);
		return MergeSorter.sortTable(q, attrs, new OrderByComparator(attrs, order), tx);
	}

	@Override
	public int blockAccessed() {
		double t = (double)(Page.BLOCK_SIZE)/TableToken.getTupleLength(q.getSchema());
		return (int)(Math.ceil(q.outputSize() / t));
	}

	@Override
	public int distinctSize(Attribute attr) {
		return q.distinctSize(attr);
	}

	@Override
	public int outputSize() {
		return q.outputSize();
	}
	
	@Override
	public Schema getSchema() {
		return q.getSchema();
	}

}
